import { Device } from "@/api/interface/iot";
import { getHistoryData } from "@/api/modules/iot/data";
import { setSensor } from "@/api/modules/model/sensor";
import AirConditioner1Img from "@/assets/images/iot/device/deviceInfo/airConditioner1.png";
import AirConditioner2Img from "@/assets/images/iot/device/deviceInfo/airConditioner2.png";
import Cold from "@/assets/images/iot/device/deviceInfo/cold.png";
import ColdActive from "@/assets/images/iot/device/deviceInfo/cold_active.png";
import FsImg from "@/assets/images/iot/device/deviceInfo/fs.png";
import HjwdImg from "@/assets/images/iot/device/deviceInfo/hjwd.png";
import Hot from "@/assets/images/iot/device/deviceInfo/hot.png";
import HotActive from "@/assets/images/iot/device/deviceInfo/hot_active.png";
import KgImg from "@/assets/images/iot/device/deviceInfo/kg.png";
import KgActive from "@/assets/images/iot/device/deviceInfo/kg_active.png";
import Moist from "@/assets/images/iot/device/deviceInfo/moist.png";
import MoistActive from "@/assets/images/iot/device/deviceInfo/moist__active.png";
import MsImg from "@/assets/images/iot/device/deviceInfo/ms.png";
import Wind from "@/assets/images/iot/device/deviceInfo/wind.png";
import WindActive from "@/assets/images/iot/device/deviceInfo/wind__active.png";
import YxImg from "@/assets/images/iot/device/deviceInfo/yx.png";
import Echarts from "@/components/Echart";
import air from "@/assets/images/iot/snapshot/1.png";
import { AuthBtns, SchemaNodeKey } from "@/utils/constants";
import mittBus from "@/utils/mittBus";
import { filterEnum, showTips } from "@/utils/util";
import { PropType, defineComponent, reactive, ref } from "vue";
import { useRoute } from "vue-router";
import "./index.scss";
import { dayjs } from "element-plus";
export default defineComponent({
	name: "AirConditioner", // 动态引入需要
	label: "空调", // 动态引入需要
	image: air, // 动态引入需要
	props: {
		detail: {
			type: Object as PropType<Device.ResDeviceInfo>,
			default() {
				return {};
			}
		}
	},
	setup() {
		return () => {
			return (
				<div class="airConditioner">
					<div class="l">
						<LT />
						<LB />
					</div>
					<div class="r">
						<RT />
						<RB />
					</div>
				</div>
			);
		};
	}
});
const modeDict = [
	{ dictLabel: "制冷", dictValue: 0 },
	{ dictLabel: "制热", dictValue: 1 },
	{ dictLabel: "换风", dictValue: 2 },
	{ dictLabel: "除湿", dictValue: 3 }
];
const windDict = [
	{ dictLabel: "自动", dictValue: 0 },
	{ dictLabel: "低", dictValue: 1 },
	{ dictLabel: "中", dictValue: 2 },
	{ dictLabel: "高", dictValue: 4 }
];
const dictData = { label: "dictLabel", value: "dictValue" };
const LT = defineComponent({
	setup() {
		return () => (
			<div class="t">
				<el-image fit="fill" class="img1" src={AirConditioner1Img} alt="" />
				<el-image fit="fill" class="img2" src={AirConditioner2Img} alt="" />
			</div>
		);
	}
});

const LB = defineComponent({
	setup() {
		const route = useRoute();
		const profile = inject<any>(SchemaNodeKey.profile);
		const sensorValue = ref({ mode: 0, onoff: 0, set_temp: 24, temp: 23, timestamp: "", wind: 0 });
		watch(
			() => profile.value,
			() => {
				init();
			}
		);
		const echartRef = ref();
		const init = () => {
			sensorValue.value = profile.value.profile?.sensor || {};
			option.series[0].data[0].value = sensorValue.value.set_temp;
			echartRef.value.setchartOption(option);
		};

		const status = [
			{
				name: filterEnum(0, modeDict, dictData),
				log: Cold,
				active: ColdActive,
				key: 4
			},
			{
				name: filterEnum(1, modeDict, dictData),
				log: Hot,
				key: 3,
				active: HotActive
			},
			{
				name: filterEnum(2, modeDict, dictData),
				log: Wind,
				key: 1,
				active: WindActive
			},
			{
				name: filterEnum(3, modeDict, dictData),
				log: Moist,
				key: 2,
				active: MoistActive
			}
		];

		const marks = {
			0: {
				style: {
					color: "#222",
					lineHeight: "40px",
					fontWeight: 500,
					fontSize: "14px"
				},
				label: filterEnum(0, windDict, dictData)
			},
			1: {
				style: {
					color: "#222",
					lineHeight: "40px",
					fontWeight: 500,
					fontSize: "14px"
				},
				label: filterEnum(1, windDict, dictData)
			},
			2: {
				style: {
					color: "#222",
					lineHeight: "40px",
					fontWeight: 500,
					fontSize: "14px"
				},
				label: filterEnum(2, windDict, dictData)
			},
			4: {
				style: {
					color: "#222",
					lineHeight: "40px",
					fontWeight: 500,
					fontSize: "14px"
				},
				label: filterEnum(4, windDict, dictData)
			}
		};
		let option = reactive({
			series: [
				{
					name: "Pressure",
					type: "gauge",
					startAngle: 180,
					endAngle: 0,
					center: ["50%", "75%"],
					radius: "90%",
					min: 16,
					max: 36,
					progress: {
						show: true,
						itemStyle: {
							borderCap: "round"
						}
					},
					pointer: {
						icon: "circle",
						length: "195%",
						width: 30,
						offsetCenter: [14, "0%"],
						itemStyle: {
							color: "#fff",
							borderWidth: 1,
							borderColor: "rgba(0, 0, 0, .16)"
						}
					},
					detail: {
						show: false
					},
					axisTick: {
						show: false
					},
					splitLine: {
						show: false
					},
					axisLabel: {
						show: false
					},
					data: [
						{
							value: 0
						}
					]
				}
			]
		});
		onMounted(() => {
			nextTick(() => {
				echartRef.value.setOption(option);
				echartRef.value.chartInit();
			});
		});
		const changeValue = (flg: boolean, setTemp?: boolean) => {
			if (!setTemp) {
				flg ? sensorValue.value.set_temp++ : sensorValue.value.set_temp--;
				sensorValue.value.set_temp <= 16 ? (sensorValue.value.set_temp = 16) : "";
				sensorValue.value.set_temp >= 36 ? (sensorValue.value.set_temp = 36) : "";
			}
			option.series[0].data[0].value = sensorValue.value.set_temp;
			echartRef.value.setchartOption(option);
			saveProfile();
		};
		const changeType = (key: number) => {
			// sensorValue.value.onoff = 1;
			sensorValue.value.mode = key;
			saveProfile();
		};
		const saveProfile = async () => {
			let param: any = {
				mode: sensorValue.value.mode,
				onoff: sensorValue.value.onoff,
				set_temp: sensorValue.value.set_temp,
				wind: sensorValue.value.wind
			};
			if (!param.onoff) {
				//关机时，不能下发设置模式、温度和风速
				param.mode = { onoff: param.onoff };
			} else if (param.onoff) {
				//开机，默认设置为制冷
				if (!param.mode) {
					let month = new Date().getMonth() + 1;
					//5~10月份，默认制冷
					param.mode = month >= 5 && month <= 10 ? 4 : 3;
				}
				if (!param.wind) {
					param.wind = 1;
				}
			}
			console.log(param);
			setSensor({
				idSn: route.query.sn,
				data: param
			}).then(res => {
				let ok = showTips(res.code, "参数设置", res.message);
				if (ok) {
					mittBus.emit("refreshDeviceDetail");
				}
			});
		};
		const disabledMod = inject<any>(AuthBtns.disabledMod);
		return () => (
			<div class="b">
				<div class="tb">
					<span>远程控制</span>
				</div>
				<div class="bl">
					<div class="pro">
						<Echarts class="proEchart" ref={echartRef} />
						<el-popover placement="top" width={300} trigger="click">
							{{
								reference: () => {
									return <span>{sensorValue.value?.set_temp}℃</span>;
								},
								default: () => {
									return (
										<div class="flex items-center">
											<div class="w-20">设置温度：</div>
											<div class="flex-1 flex items-center">
												<el-input
													class="flex-1"
													v-model={sensorValue.value.set_temp}
													disabled={disabledMod.value}
													onKeyup={(e: KeyboardEvent) => (e.keyCode == 13 ? changeValue(false, true) : null)}
												/>
												<el-button type="primary" disabled={disabledMod.value} onClick={() => changeValue(false, true)}>
													确定
												</el-button>
											</div>
										</div>
									);
								}
							}}
						</el-popover>
					</div>
					<div class="btn">
						<el-button
							disabled={disabledMod.value}
							class="btnList"
							onClick={() => {
								changeValue(false);
							}}
						>
							<span class="iconfont iconminus1" />
						</el-button>
						<img
							class={disabledMod.value ? "disFunc" : ""}
							src={sensorValue.value?.onoff == 0 ? KgImg : KgActive}
							onClick={() => {
								sensorValue.value.onoff = sensorValue.value.onoff == 0 ? 1 : 0;
								saveProfile();
							}}
						/>
						<el-button
							disabled={disabledMod.value}
							class="btnList "
							onClick={() => {
								changeValue(true);
							}}
						>
							<span class="iconfont iconplus"></span>
						</el-button>
					</div>
				</div>
				<div class="br">
					<p class="title">模式</p>
					<ul>
						{status.map(item => {
							return (
								<li
									class={disabledMod.value ? "disFunc" : ""}
									onClick={() => {
										changeType(item.key);
									}}
								>
									<div class="img">
										<img src={item.key === sensorValue.value?.mode ? item.active : item.log} alt="" />
									</div>
									<span>{item.name}</span>
								</li>
							);
						})}
					</ul>
					<p class="title">风速</p>
					<div class="slider">
						<el-slider
							disabled={disabledMod.value}
							v-model={sensorValue.value.wind}
							marks={marks}
							max={4}
							min={0}
							onChange={saveProfile}
						/>
					</div>
				</div>
			</div>
		);
	}
});
const RT = defineComponent({
	setup() {
		const profile = inject<any>(SchemaNodeKey.profile);
		const sensorValue = ref();
		const echartRef = ref();
		const status = ref<any>([]);
		watch(
			() => profile.value,
			() => {
				init();
			}
		);
		const init = () => {
			sensorValue.value = profile.value.profile?.sensor;
			option.series[0].data[0].value = sensorValue.value?.temp;
			echartRef.value.setchartOption(option);
			status.value = [
				{
					img: YxImg,
					label: "运行状态",
					value: sensorValue.value?.onoff == 0 ? "关" : "开"
				},
				{
					img: HjwdImg,
					label: "室内温度",
					value: sensorValue.value?.temp + "℃"
				},
				{
					img: FsImg,
					label: "风速",
					value: filterEnum(sensorValue.value?.wind, windDict, dictData)
				},
				{
					img: MsImg,
					label: "运行模式",
					value: filterEnum(sensorValue.value?.mode, modeDict, dictData)
				}
			];
		};
		let option = reactive({
			series: [
				{
					type: "gauge",
					progress: {
						show: true,
						width: 20,
						itemStyle: {
							color: {
								type: "linear",
								x: 0,
								y: 0,
								x2: 0,
								y2: 1,
								colorStops: [
									{
										offset: 1,
										color: "#3CF57D" // 0% 处的颜色
									},
									{
										offset: 0,
										color: "#FFAB19" // 100% 处的颜色
									}
								],
								global: false // 缺省为 false
							}
						}
					},
					startAngle: 180,
					endAngle: 0,
					center: ["50%", "75%"],
					radius: "90%",
					min: 16,
					max: 36,
					splitNumber: 5,
					splitLine: {
						distance: -30,
						length: 30,
						lineStyle: {
							color: "#fff",
							width: 10
						}
					},
					axisLine: {
						lineStyle: {
							width: 20,
							color: [
								[0.25, "#E6EBF5"],
								[0.5, "#E6EBF5"],
								[0.75, "#E6EBF5"],
								[1, "#E6EBF5"]
							]
						}
					},
					axisLabel: {
						distance: 50
					},
					pointer: {
						show: false
					},
					axisTick: {
						length: 12,
						lineStyle: {
							color: "#D5DFF1",
							width: 2
						}
					},
					title: {
						show: false
					},
					detail: {
						fontSize: 30,
						offsetCenter: [0, "-10%"],
						valueAnimation: true,
						formatter: function (value: number) {
							return Math.round(value) + "℃";
						},
						color: "#000"
					},
					data: [
						{
							value: "",
							name: "Grade Rating"
						}
					]
				}
			]
		});
		onMounted(() => {
			nextTick(() => {
				echartRef.value.setOption(option);
				echartRef.value.chartInit();
			});
		});

		return () => (
			<div class="rt">
				<div class="tb">
					<span>设备状态</span>
				</div>
				<div class="rtl">
					<Echarts class="chartBox" ref={echartRef} />
					<div class="btn">当前温度</div>
				</div>
				<div class="rtr">
					{status.value.map((item: any) => {
						return (
							<dl>
								<dt>
									<img src={item.img} alt="" />
								</dt>
								<dd>
									<span>{item.label}</span>
									<p>{item.value}</p>
								</dd>
							</dl>
						);
					})}
				</div>
			</div>
		);
	}
});
const RB = defineComponent({
	setup() {
		const route = useRoute();
		const echartRef = ref();
		let option = reactive({
			xAxis: {
				type: "category",
				data: [] as string[],
				axisLine: {
					lineStyle: {
						color: "#D9D9D9",
						width: 1,
						type: "dashed"
					}
				},
				axisTick: {
					show: false
				},
				axisLabel: {
					color: "#000000",
					fontSize: 13,
					fontWeight: 500,
					show: true
				}
			},
			legend: {
				data: ["设置温度", "室内温度"],
				left: 25,
				top: 0
			},
			tooltip: {
				show: true,
				trigger: "axis"
			},
			yAxis: {
				type: "value",
				axisLine: {
					show: false
				},
				axisLabel: {
					formatter: "{value}",
					color: "000000",
					fontSize: 13,
					fontWeight: 500
				},
				splitLine: {
					lineStyle: {
						color: "#D9D9D9",
						type: [5, 5],
						dashOffset: 3
					}
				}
			},
			series: [
				{
					name: "设置温度",
					smooth: 0.6,
					symbol: "circle",
					symbolSize: 6,
					itemStyle: {
						// 设置symbol的颜色
						normal: {
							color: "#82E28D"
						}
					},
					lineStyle: {
						color: "#82E28D",
						width: 5
					},
					type: "line",
					areaStyle: {
						color: {
							//线性渐变
							type: "linear",
							x: 0,
							y: 0,
							x2: 0,
							y2: 1,
							colorStops: [
								{
									offset: 0,
									color: "rgba(130, 226, 141,0.8)" // 0% 处的颜色
								},
								{
									offset: 1,
									color: "rgba(130, 226, 141,0)" // 100% 处的颜色
								}
							],
							global: false // 缺省为 false
						}
					},
					data: []
				},
				{
					name: "室内温度",
					smooth: 0.6,
					symbol: "circle",
					symbolSize: 6,
					itemStyle: {
						// 设置symbol的颜色
						normal: {
							color: "#63ACFF"
						}
					},
					lineStyle: {
						color: "#63ACFF",
						width: 5
					},
					type: "line",
					areaStyle: {
						color: {
							//线性渐变
							type: "linear",
							x: 0,
							y: 0,
							x2: 0,
							y2: 1,
							colorStops: [
								{
									offset: 0,
									color: "rgba(99, 172, 255,0.8)" // 0% 处的颜色
								},
								{
									offset: 1,
									color: "rgba(99, 172, 255,0)" // 100% 处的颜色
								}
							],
							global: false // 缺省为 false
						}
					},
					data: []
				}
			],
			grid: {
				left: 60,
				top: 40,
				right: 40,
				bottom: 100
			}
		});
		const initTemp = async () => {
			option.xAxis.data = [];
			option.series[0].data = [];
			let { result } = await getHistoryData({
				pageIndex: 1,
				pageSize: 1000,
				idSn: route.query.sn as string,
				key: "set_temp",
				keyType: "sensor",
				startTime: dayjs(data.dateTraffic[0]).format(),
				endTime: dayjs(data.dateTraffic[1]).format()
			});
			if (result.records && result.records.length) {
				option.xAxis.data = result.records.map((item: any) => item.updateTime);
				option.series[0].data = result.records.map((item: any) => item.value);
			} else {
				option.xAxis.data = [];
				option.series[0].data = [];
			}
		};
		const data = reactive({
			dateTraffic: [dayjs().subtract(15, "d"), dayjs()]
		});
		const initSetTemp = async () => {
			option.series[1].data = [];
			let { result } = await getHistoryData({
				pageIndex: 1,
				pageSize: 1000,
				idSn: route.query.sn as string,
				key: "temp",
				keyType: "sensor",
				startTime: dayjs(data.dateTraffic[0]).format(),
				endTime: dayjs(data.dateTraffic[1]).format()
			});
			if (result.records && result.records.length) {
				option.series[1].data = result.records.map((item: any) => item.value);
			} else {
				option.series[1].data = [];
			}
		};
		onMounted(() => {
			nextTick(async () => {
				if (route.query.sn) {
					await initTemp();
					await initSetTemp();
				}
				echartRef.value.setOption(option);
				echartRef.value.chartInit();
			});
			mittBus.on("clickRefreshDeviceDetail", async () => {
				if (route.query.sn) {
					await initTemp();
					await initSetTemp();
				}
				echartRef.value.setOption(option);
				echartRef.value.chartInit();
			});
		});
		onBeforeUnmount(() => {
			mittBus.off("clickRefreshDeviceDetail");
		});
		return () => (
			<div class="rb">
				<div class="tb">
					<span>运行状态</span>
				</div>
				<div class=" justify-end flex p-4">
					<div>
						<el-date-picker
							style="width: 240px"
							type="daterange"
							v-model={data.dateTraffic}
							onChange={() => {
								nextTick(async () => {
									if (route.query.sn) {
										await initTemp();
										await initSetTemp();
									}
									echartRef.value.setOption(option);
									echartRef.value.chartInit();
								});
							}}
						/>
					</div>
				</div>
				<Echarts class="chartBox" ref={echartRef} />
			</div>
		);
	}
});
